package com.echo.yixiaowu.feature.components

import android.graphics.RenderEffect
import android.graphics.Shader
import android.os.Build
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectHorizontalDragGestures
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableLongStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.asComposeRenderEffect
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.vectorResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import com.echo.yixiaowu.R
import kotlinx.coroutines.delay
import kotlin.math.roundToInt

@Composable
fun VideoControl(
    modifier: Modifier,
    onToggleFullScreen: () -> Unit,
    bufferProgress: Float,
    progress: Float,
    resetHideControlTimer: () -> Unit,
    isFullScreen: Boolean,
    videoDurationString: String,
    currentDurationString: String,
    totalDuration: Long = 0L,
    currentDuration: Long = 0L,
    isShowControl: Boolean = false,
    isPlaying: Boolean,
    onPlayOrPause: () -> Unit,
    onShowControls: () -> Unit,
    onProgressChange: (Float) -> Unit,
    content: @Composable BoxScope.() -> Unit
) {

    // 记录上一次点击的时间戳，0L 表示未点击
    var lastTapTime by remember { mutableLongStateOf(0L) }
    val interactionSource = remember { MutableInteractionSource() }
    var localIsFullscreen by remember { mutableStateOf(isFullScreen) }
    var localIsPlaying by remember { mutableStateOf(isPlaying) }
    var localIsShowControl by remember { mutableStateOf(isShowControl) }
    LaunchedEffect(isFullScreen, isPlaying, isShowControl) {
        localIsFullscreen = isFullScreen
        localIsPlaying = isPlaying
        localIsShowControl = isShowControl
    }

    LaunchedEffect(lastTapTime) {
        if (lastTapTime != 0L) {
            delay(300L)

            if (System.currentTimeMillis() - lastTapTime >= 300L) {
                onShowControls() // 触发单击的动作
                lastTapTime = 0L
            }
        }
    }

    var showSeekIndicator by remember { mutableStateOf(false) }
    var seekTargetText by remember { mutableStateOf("") }

    var totalDragAmount by remember { mutableFloatStateOf(0f) }

    // thumb的位置，从子布局传输上来
    var thumbPosition by remember { mutableFloatStateOf(0f) }
    var barWidth by remember { mutableFloatStateOf(1f) }
    var isShowDrag by remember { mutableStateOf(false) }
    var newProgress by remember { mutableFloatStateOf(0f) }

    // 叠加控制面板
    // TODO:  添加功能：视频比例选择，分享功能
    Box(contentAlignment = Alignment.Center, modifier = modifier
        .pointerInput(Unit) {
            detectHorizontalDragGestures(onDragStart = {
                totalDragAmount = 0f
                showSeekIndicator = true
                localIsShowControl = true
                isShowDrag = true
            }, onHorizontalDrag = { change, dragAmount ->
                change.consume()
                // 前进距离比 = 小红点移动距离 =(当前thumb位置 + 拖动距离) / 进度条宽度(barWidth)
                thumbPosition = (thumbPosition + dragAmount * 0.4f).coerceIn(0f, barWidth)
                newProgress = thumbPosition / barWidth
                // 调整时长 = 总时长 * 前进距离比
                val targetPosition =
                    (totalDuration * newProgress).coerceIn(0f, totalDuration.toFloat()).toLong()
                seekTargetText = "${formatTime(targetPosition)} / $videoDurationString"
            }, onDragEnd = {
                localIsShowControl = false
                showSeekIndicator = false
                isShowDrag = false
                onProgressChange(newProgress)
            }, onDragCancel = {
                localIsShowControl = false
                showSeekIndicator = false
                isShowDrag = false
            })
        }
        .clickable(interactionSource = interactionSource, indication = null, onClick = {
            // 获取当前时间
            val currentTime = System.currentTimeMillis()
            // 判断是否是双击
            if (currentTime - lastTapTime < 300L) {
                // 如果时间差小于 300ms，认为是双击
                onPlayOrPause()
                lastTapTime = 0L
            } else {
                lastTapTime = currentTime // 更新上一次点击时间
            }
        })
    ) {
        content()
        AnimatedVisibility(
            visible = showSeekIndicator,
            enter = fadeIn(),
            exit = fadeOut(),
            modifier = Modifier.align(Alignment.Center)
        ) {
            SeekIndicator(
                changeText = "预览图", targetText = seekTargetText
            )
        }

        PortraitBottomBar(
            isShowControl = localIsShowControl,
            isFullscreen = localIsFullscreen,
            isPlaying = localIsPlaying,
            isShowDrag = isShowDrag,
            currentDurationString = currentDurationString,
            videoDurationString = videoDurationString,
            progress = progress,
            thumbPosition = thumbPosition,
            bufferProgress = bufferProgress,
            onPlayOrPause = onPlayOrPause,
            onProgressChange = onProgressChange,
            onToggleFullScreen = onToggleFullScreen,
            onBarWidthChange = { barWidth = it },
            onThumbChange = { thumbPosition = it }
        )
    }
}

// 底部功能
@Composable
private fun BoxScope.PortraitBottomBar(
    isShowControl: Boolean,
    isFullscreen: Boolean,
    isPlaying: Boolean,
    isShowDrag: Boolean,
    currentDurationString: String,
    videoDurationString: String,
    thumbPosition: Float,
    progress: Float,
    bufferProgress: Float,
    onPlayOrPause: () -> Unit,
    onProgressChange: (Float) -> Unit,
    onToggleFullScreen: () -> Unit,
    onBarWidthChange: (Float) -> Unit,
    onThumbChange: (Float) -> Unit,
    density: Density = LocalDensity.current
) {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .align(Alignment.BottomStart)
    ) {
        if (isShowControl) {
            Box(
                modifier = Modifier.fillMaxWidth()
            ) {
                PlayerBottomControl(
                    modifier = Modifier
                        .height(40.dp)
                        .fillMaxWidth()
                )

                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(
                            horizontal = if (isFullscreen) 32.dp else 16.dp,
                            vertical = if (isFullscreen) 0.dp else 10.dp
                        ),
                    verticalAlignment = Alignment.CenterVertically,
                ) {
                    if (isFullscreen) {
                        Spacer(modifier = Modifier.width(8.dp))
                    }
                    // 播放暂停键
                    Icon(imageVector = if (isPlaying) ImageVector.vectorResource(
                        R.drawable.ic_stop
                    )
                    else ImageVector.vectorResource(
                        R.drawable.ic_play
                    ),
                        contentDescription = if (isPlaying) "Stop" else "Play",
                        tint = Color.White,
                        modifier = Modifier
                            .size(if (isFullscreen) 32.dp else 24.dp)
                            .clickable { onPlayOrPause() })
                    Spacer(modifier = Modifier.width(8.dp))
                    // 播放时间
                    Text(
                        currentDurationString,
                        color = Color.White,
                        style = MaterialTheme.typography.labelSmall
                    )

                    Spacer(modifier = Modifier.width(14.dp))
                    Box(Modifier.weight(1f)) {
                        // 进度条
                        VideoProgressBar(
                            isShowThumb = true,
                            isShowDrag = isShowDrag,
                            bufferProgress = bufferProgress,
                            progress = progress,
                            thumbPosition = thumbPosition,
                            onProgressChange = { onProgressChange(it) },
                            onBarWidthChange = onBarWidthChange,
                            onThumbChange = onThumbChange
                        )
                    }

                    Spacer(modifier = Modifier.width(14.dp))
                    // 视频总时长
                    Text(
                        videoDurationString,
                        color = Color.White,
                        style = MaterialTheme.typography.labelSmall
                    )

                    Spacer(modifier = Modifier.width(8.dp))
                    // 全屏按钮
                    Icon(
                        modifier = Modifier
                            .size(if (isFullscreen) 32.dp else 24.dp)
                            .clickable { onToggleFullScreen.invoke() },
                        imageVector = ImageVector.vectorResource(
                            if (isFullscreen) R.drawable.ic_exit_full_screen
                            else R.drawable.ic_fullscreen
                        ),
                        contentDescription = if (isFullscreen) "Exit Fullscreen" else "Fullscreen",
                        tint = Color.White
                    )
                }
            }
        }

        if (!isFullscreen && !isShowControl) {
            VideoProgressBar(
                modifier = Modifier.offset {
                    with(density) {
                        IntOffset(0, 7.dp.toPx().roundToInt())
                    }
                },
                isShowColor = false,
                isShowThumb = false,
                progress = progress,
                bufferProgress = bufferProgress,
                trackHeight = 2.dp,
                thumbPosition = thumbPosition,
            )
        }
    }
}

// 一个模糊透明的图层
@Composable
private fun PlayerBottomControl(modifier: Modifier = Modifier) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
        Box(modifier = modifier
            .graphicsLayer {
                val blurEffect = RenderEffect.createBlurEffect(
                    8f, 8f, Shader.TileMode.CLAMP
                )
                renderEffect = blurEffect.asComposeRenderEffect()
                alpha = 0.99f
            }
            .background(
                Brush.verticalGradient(
                    colorStops = arrayOf(
                        0.0f to Color.Black.copy(alpha = 0.01f),
                        0.4f to Color.Black.copy(alpha = 0.3f),
                        1.0f to Color.Black.copy(alpha = 0.7f)
                    )
                )
            ))
    } else {
        Box(
            modifier = modifier.background(
                Brush.verticalGradient(
                    colorStops = arrayOf(
                        0.0f to Color.Transparent,
                        0.4f to Color.Black.copy(alpha = 0.3f),
                        1.0f to Color.Black.copy(alpha = 0.7f)
                    )
                )
            )
        )
    }
}

@Composable
@Preview
private fun VideoProgressIndicatorPreview1() {
    VideoProgressBar(
        isShowThumb = false, progress = 0.5f, trackHeight = 6.dp
    )
}